package net.myjung.workbench;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.myjung.content.CttFactory;
import net.myjung.content.CttText;

import org.apache.commons.io.IOUtils;

public class WriteFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public WriteFileServlet() {
		super();
	}
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String fileName = request.getParameter("fileName");
		String value = null;
		try {
			CttText text = CttFactory.getManager().getText(id, null);
			if (text != null && text.getData() != null)
				value = text.getData();
			if (value == null || value.equals("")) {
				value = " ";
			} else {
//				value = StringUtils.replace(value, "\r", "\r\n");
			}
		} catch (Exception e) {
			throw new ServletException(e);
		}
		
		ServletContext context = getServletContext();
		String mimeType = context.getMimeType(fileName);
		response.setContentType(mimeType == null? "text/plain" : mimeType);
		response.setHeader("Content-Disposition", "attachment; fileName=\"" + fileName + "\"");

		OutputStream os = null;
		InputStream is = null;
		try {
			os = response.getOutputStream();
			is = IOUtils.toInputStream(value, "MS949");

			int len;
			byte[] buffer = new byte[10240];
			while ((len = is.read(buffer, 0, buffer.length)) != -1)
				os.write(buffer, 0, len);
//			os.write(value.getBytes("MS949"));
			
		} catch (Exception e) {
			throw new ServletException(e);
		} finally {
			if (is != null)
				is.close();
			if (os != null) {
				os.flush();
				os.close();
			}
		}
	}
}
